
package com.simple.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dfe.common.exception.RRException;
import com.dfe.common.utils.Constant;
import com.dfe.common.utils.PageUtils;
import com.dfe.common.utils.Query;
import com.dfe.modules.sys.dao.SysUserDao;
import com.dfe.modules.sys.entity.SysUserEntity;
import com.dfe.modules.sys.service.SysRoleService;
import com.dfe.modules.sys.service.SysUserRoleService;
import com.dfe.modules.sys.service.SysUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysUserEntity> iPage = new Query<SysUserEntity>().getPage(params);
        QueryWrapper<SysUserEntity> qw = new QueryWrapper<SysUserEntity>()
                .eq(params.get("isUrgencyDuty") != null, "is_urgency_duty", params.get("isUrgencyDuty"))
                .like(params.get("userName") != null, "user_name", params.get("userName"));

        IPage<SysUserEntity> page = page(iPage, qw);

        List<Integer> roleIdList;
        for (SysUserEntity user : page.getRecords()){
            roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
            user.setRoleIdList(roleIdList);
        }

        return new PageUtils(page);
    }

    @Override
    public List<Integer> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String userName) {
        QueryWrapper<SysUserEntity> qw = new QueryWrapper<SysUserEntity>()
                .eq("user_name",userName);
        return getOne(qw);
    }

    @Override
    public void saveUser(SysUserEntity user) {
        if (user.getPassword() == null){
            user.setPassword("123456");
        }
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        save(user);
        //检查角色是否越权
        checkRole(user);
        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public void updateUser(SysUserEntity user) {
        SysUserEntity history = getById(user.getUserId());
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(history.getPassword());
        } else {
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        }

        //检查角色是否越权
        checkRole(user);
        updateById(user);
        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }



    @Override
    public void updateUserStatusByLoginTime(Long userId, Integer flag) {
        SysUserEntity user = getById(userId);
        if (flag == 0){
            user.setFailLoginTime(user.getFailLoginTime() + 1);
        }else {
            user.setFailLoginTime(0);
        }

        if (user.getFailLoginTime() >=5 ){
            user.setStatus(0);
        }
        updateById(user);
    }

    @Override
    public Boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        userEntity.setPasswordUpdateTime(new Date());
        return update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user) {
        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
            return;
        }

        //查询用户创建的角色列表
        List<Integer> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

        //判断是否越权
        if (!roleIdList.containsAll(user.getRoleIdList())) {
            throw new RRException("新增用户所选角色，不是本人创建");
        }
    }
}